import {
  getArticleCommentById,
  getArticleCommentAll,
  getArticleCommentPageList,
  commonUpdate,
  updateArticleComment,
  addArticleComment,
  deleteArticleComment
} from '@/services/articleCommentService';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, message, Popconfirm, Space, Typography } from 'antd';
import React, { useRef, useState } from 'react';

/**
 *
 * @constructor
 */
const ArticleCommentPage: React.FC<unknown> = () => {
  const [updateData, setUpdateData] = useState<ArticleCommentType.ArticleComment>(
    {} as ArticleCommentType.ArticleComment,
  );
  const actionRef = useRef<ActionType>();

  /**
   *
   * @param
   */
  const doDelete = async (model: ArticleCommentType.ArticleComment) => {
    const hide = message.loading('正在删除');
    if (!model?.Id) {
      return;
    }
    try {
      await deleteArticleComment({
        id: model.Id,
      });
      message.success('操作成功');
      actionRef.current?.reload();
    } catch (e: any) {
      message.error('操作失败，' + e.message);
    } finally {
      hide();
    }
  };

  const checkArticleComment = async (record: ArticleCommentType.ArticleCommentResponse) => {
    const { StatusCode } = await commonUpdate(record.Id, "Status", "1");
    if (StatusCode === 0) {
      message.success("审核成功！");
      actionRef.current?.reload();
    }
  }

  const refuseArticleComment = async (record: ArticleCommentType.ArticleCommentResponse) => {
    const { StatusCode } = await commonUpdate(record.Id, "Status", "2");
    if (StatusCode === 0) {
      message.success("拒绝成功！");
      actionRef.current?.reload();
    }
  }

  const transferArticle = (articleId: number) => {
    console.log(articleId)
  }

  /**
   *
   */
  const columns: ProColumns<ArticleCommentType.ArticleCommentResponse>[] = [

    {
      title: 'id',
      dataIndex: 'Id',
      hideInSearch: true,
    },

    {
      title: '评论内容',
      dataIndex: 'Comment',
    },

    {
      title: '评论人',
      dataIndex: 'AddUserId',
      hideInSearch: true,
      render(dom, entity) {
        return <span>{entity.AddUser?.UserName ?? ''}</span>
      },
    },
    {
      title: '评论时间',
      dataIndex: 'AddTime',
      hideInSearch: true
    },

    {
      title: '文章链接',
      dataIndex: 'ArticleId',
      hideInSearch: true,
      render(dom, entity) {
        return <span key={entity.ArticleId} onClick={() => transferArticle(entity.ArticleId)}>{entity.ArticleInfo?.Title.length > 50 ? entity.ArticleInfo?.Title.substring(0, 50) : entity.ArticleInfo?.Title}</span>
      },
    },

    {
      title: '状态',
      dataIndex: 'Status',
      hideInSearch: true,
      render(dom, entity) {
        const statusEnum = ["待审核", "审核通过", "未通过"];
        return statusEnum[entity.Status];
      }
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_: any, record: ArticleCommentType.ArticleCommentResponse) => (
        <Space split={<Divider type="vertical" />}>
          <Popconfirm
            title="您确定审核么？"
            onConfirm={() => checkArticleComment(record)}
            okText="确认"
            cancelText="取消"
          >
            <Typography.Link
              disabled={record.Status === 1}
              onClick={() => {
              }}
            >
              审核
            </Typography.Link>
          </Popconfirm>
          <Popconfirm
            title="您确定拒绝么？"
            onConfirm={() => refuseArticleComment(record)}
            okText="确认"
            cancelText="取消"
          >
            <Typography.Link
              disabled={record.Status === 2}
              style={{ color: record.Status !== 2 ? "green" : "" }}
              onClick={() => {
              }}
            >
              拒绝
            </Typography.Link>
          </Popconfirm>
          <Popconfirm
            title="您确定要删除么？"
            onConfirm={() => doDelete(record)}
            okText="确认"
            cancelText="取消"
          >
            <Typography.Link type="danger">删除</Typography.Link>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<ArticleCommentType.ArticleCommentResponse>
        headerTitle="评论管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        toolBarRender={() => [
        ]}
        request={async (params: any, sorter: any) => {
          const searchParams: PageInfo.PageRequest = {
            pageSize: params.pageSize,
            current: params.current
          };

          let sortQuery = "", filterQuery = "";
          // eslint-disable-next-line guard-for-in
          for (const key in sorter) {
            sortQuery += `${key}|${sorter[key]}`;
          }

          if (sortQuery != "") {
            searchParams['@sort'] = sortQuery;
          }

          for (const key in params) {
            if (key !== "pageSize" && key !== "current") {
              if (params[key] != "") {
                filterQuery += `contains(${key},${params[key]})&`;
                params[key] = '';
              }
            }
          }

          if (filterQuery != "") {
            searchParams['@filter'] = filterQuery;
          }

          searchParams['@relationships'] = "UserInfo,ArticleInfo";
          const { Items, StatusCode } = await getArticleCommentPageList(searchParams);
          return {
            data: Items[0]?.Records || [],
            success: StatusCode === 200,
            total: Items[0].Total,
          } as any;
        }}
        columns={columns}
      />
    </PageContainer>
  );
};

export default ArticleCommentPage;
